<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Controller\AbstractController;
use Hyperf\Di\Annotation\Inject;
use App\Utils\ApiUtils;
use App\Service\ManageService;
use App\Constants\ErrorCode;
use App\Validate\AdminValidation;

class ManageController extends AbstractController
{

    /**
     * @Inject 
     * @var ManageService
     */
    protected $service;

    //获取管理员列表
    public function list()
    {
        $page = $this->request->input('page', 1);
        $pageSize = $this->request->input('pageSize', 15);
        $name = $this->request->input('name', '');
        $result = $this->service->list($name,$page,$pageSize);
        return $this->response->json(ApiUtils::send(ErrorCode::SUCCESS,'获取成功',$result['data'],intval($result['count'])));
        
        
    }

    //添加管理员
    public function add()
    {
        //接收参数
        $data['name'] = $this->request->input('name');
        $data['password'] = $this->request->input('password');
        $data['remark'] = $this->request->input('remark', '');
        $data['role_id'] = $this->request->input('role_id');
        make(AdminValidation::class)->check($data,'add')->response();
        $result = $this->service->add($data);
        return $this->response->json(ApiUtils::send(ErrorCode::SUCCESS,'添加成功',$result));
        
    }

    //编辑管理员
    public function edit()
    {
        $id = $this->request->input('id');
        if($this->request->isMethod('post')){
            //接收参数
            $data['id'] = $id;
            $data['name'] = $this->request->input('name');
            $data['password'] = $this->request->input('password', '');
            $data['remark'] = $this->request->input('remark', '');
            $data['role_id'] = $this->request->input('role_id');
            make(AdminValidation::class)->check($data,'edit_post')->response();
            $result = $this->service->editPost($data);
            return $this->response->json(ApiUtils::send(ErrorCode::SUCCESS,'修改成功'));

        }
        make(AdminValidation::class)->check(['id'=>$id],'edit_get')->response();
        $result = $this->service->editGet($id);
        return $this->response->json(ApiUtils::send(ErrorCode::SUCCESS,'获取成功',$result));
        
        
    }


    //删除管理员
    public function del()
    {
        $id = $this->request->input('id');
        make(AdminValidation::class)->check(['id'=>$id],'edit_get')->response();
        $result = $this->service->del($id);
        return $this->response->json(ApiUtils::send(ErrorCode::SUCCESS,'删除成功'));
       
    }

    //重置密码
    public function password(){
        make(AdminValidation::class)->check($this->request->all(),'reset_pass')->response();
        $this->service->password($this->request->all());
        return $this->response->json(ApiUtils::send(ErrorCode::SUCCESS,'操作成功'));
    }
   
}
